/*
 * @Author: song
 * @Description:序列化string => 文件夹特性
 * @Date: 2024年04月19日 星期五 11:04:47
 * @Modify:
 */

using System;
using UnityEngine;

namespace Function.SerializedPropertyAttribute
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
    public class DirectoryFieldAttribute : PropertyAttribute
    {
    }
}

#if UNITY_EDITOR
namespace Function.SerializedPropertyAttribute
{
    using UnityEditor;

    [CustomPropertyDrawer(typeof(DirectoryFieldAttribute))]
    public class DirectoryFieldAttributeAttribute : PropertyDrawer
    {
        private DirectoryFieldAttribute Attribute =>
            _attribute ??= attribute as DirectoryFieldAttribute;

        private DirectoryFieldAttribute _attribute;

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            EditorGUI.BeginChangeCheck();
            var folderAsset =
                EditorGUILayout.ObjectField(label,
                    AssetDatabase.LoadAssetAtPath<DefaultAsset>(property.stringValue), typeof(DefaultAsset), false);
            if (EditorGUI.EndChangeCheck())
            {
                // 当检测到拖拽操作变更时，更新folderPath字段为新的文件夹路径
                if (folderAsset != null)
                {
                    // 保存文件夹路径
                    string path = AssetDatabase.GetAssetPath(folderAsset);
                    property.stringValue = path;
                    property.serializedObject.ApplyModifiedProperties();
                }
            }
        }
    }
}
#endif